<template>
<div>
  <div id="printHtml" v-html="showPrint" style="position: absolute;top: -9999px;left: -9999px;" ></div>
  <el-dialog destroy-on-close close-on-press-escape v-model="chosePrint" title="打印小票" @close="hide">
    <div v-if="showTitle" style="text-align: center;font-size: 22px;">装车成功</div>
    <div style="margin-top: 60px;text-align: center;">
      <el-button   @click="toPrint(1)" type="primary" style=" width: 180px;height: 50px;">打印 小票</el-button>
    </div>
    <div style="height: 100px;"></div>
    <div style="margin-top: 50px;text-align: center;margin-bottom: 50px;" v-if="showPrintAdd">
      <lbtn   @click="toPrint(4)"  style=" width: 180px;height: 50px;" ><i class="fa fa-plus"  /> 新增 装车</lbtn >
    </div>
  </el-dialog>
</div>
</template>

<script>
import tool from "@/utils/tool";
import xe from 'xe-utils'
export default {
  name: "doprint",
  props: {
    showTitle: {type: Boolean, default: false},
    showPrintBill: {type: Boolean, default: true},
    showPrintBoth: {type: Boolean, default: true},
    showPrintAdd: {type: Boolean, default: false},
  },
  data () {
    return {
      showPrint: '',
      chosePrint: false, // 选择打印类型
      printItem: {},
      sendPrintName: '',
      salePrintName: '',
      printDetail: [] // 需要打印明细的租户
    }
  },
  created () {
    this.getPrintName()
    tool.post('deliver/printDetail', {}).then(ret => {
      for (let i = 0; i < ret.data.length; i++) {
        if (ret.data[i].print) {
          this.printDetail.push(ret.data[i].tenantId)
        }
      }
    })
  },
  methods: {
    // 取打印机名称
    getPrintName () {
      tool.post('deliver/getPrintName', {}).then(ret => {
        if (ret.stat) {
          if (ret.data.length === 0) return tool.err('没有发现打印机')
          let sendPrints = []
          let salePrints = []
          for (let i = 0; i < ret.data.length; i++) {
            if (ret.data[i].sendPrintName) sendPrints.push(ret.data[i].sendPrintName.trim())
            if (ret.data[i].salePrintName) salePrints.push(ret.data[i].salePrintName.trim())
          }
          const LODOP = (typeof getCLodop === 'function') ? getCLodop() : ''
          if (LODOP) {
            let c = LODOP.GET_PRINTER_COUNT()
            if (!c) return tool.err('未发现打印机')
            for (let i = 0; i < c; i++) {
              let name = LODOP.GET_PRINTER_NAME(i)
              if (!name) continue
              if (sendPrints.indexOf(name.trim()) !== -1) {
                this.sendPrintName = name
              }
              if (salePrints.indexOf(name.trim()) !== -1) {
                this.salePrintName = name
              }
            }
          }
        }
      })
    },
    // 打印
    print (item) {
      // 同时打印票据 和 送货单
      const LODOP = (typeof getCLodop === 'function') ? getCLodop() : ''
      if (LODOP) {
        LODOP.SET_PRINT_MODE('CATCH_PRINT_STATUS', true)
        // tool.post('deliver/getPrint', {cargoId: item.id}).then(ret => {
        //   if(ret.stat) {
        //     console.log(ret.data)
        //   }
        // })
        this.printItem = item
        this.chosePrint = true
      }
      else {
        tool.err('没有打印驱动')
      }
    },
    toPrint (index) {
      let item = this.printItem
      if(index === 1) {
        if (!this.sendPrintName) return tool.err('没有设置小票打印机')
        this.sendPrint(item, this.sendPrintName)
      }
      if(index === 2) {
        if (!this.salePrintName) return tool.err('没有设置票据打印机')
        this.salePrint(item, this.salePrintName)
      }
      if(index === 3) {
        if (!this.sendPrintName) return tool.err('没有设置小票打印机')
        if (!this.salePrintName) return tool.err('没有设置票据打印机')
        this.salePrint(item, this.salePrintName)
        //
        this.sendPrint(item, this.sendPrintName)
      }
      if (index === 4) {
        this.$emit('addNew')
        setTimeout(() => {
          this.chosePrint = false
        }, 50)
      }
    },
    // 打印单据
    salePrint(item, salePrintName) {
      tool.post('bill/getPrintByCargoId', {cargoId: item.id}).then(ret => {
        if (ret.stat && ret.data) {
          if (LODOP.SET_PRINTER_INDEX(salePrintName)) {
            let data = ret.data
            let evals = data.evals
            let taskId = data.task_id
            LODOP.SET_LICENSES("","C748D766DD08B5AE84E6BC2F3A546E6C7C9","","");
            for (let i = 0; i < evals.length; i++) {
              let str = evals[i].str
              if (str) {
                eval(str)
              }
              else {
                let data = evals[i].data
                LODOP.ADD_PRINT_TABLE(0,15,'96%','100%', data)
              }
            }
            this.chosePrint = false
            if (LODOP.CVERSION)
              CLODOP.On_Return = (TaskID,Value)=> {
                if (Value !== 0 || Value !== false) {
                  tool.post('print/printSuc', {taskId: taskId}).then(ret => {})
                }
              }
          } else {
            tool.err('读取票据打印机失败')
          }
        }
      })
    },
    // 打印小票
    sendPrint(item, sendPrintName) {
      let cargo = item.cargo.filter(row => {
        return row.transType !== 150602
      })
      let sumCount = 0
      for (let i = 0; i < cargo.length; i++) {
        sumCount += xe.toNumber(cargo[i].qty)
      }
      let gpGoods = this.groupGoods(cargo) // 商品汇总
      let gpBu = xe.groupBy(cargo, 'buName')
      let gpCargo = [] // 明细
      for(let i in gpBu) {
        let r = gpBu[i][0]
        let subCount = 0
        for (let j = 0; j < gpBu[i].length; j++) {
          subCount += xe.toNumber(gpBu[i][j].qty)
        }
        let ret = {
          buName: r.buName,
          address: r.address,
          linkName: r.linkName,
          linkMobile: r.linkMobile,
          tenantId: r.tenantId,
          goods: this.groupGoods(gpBu[i]),
          subCount: subCount
        }
        gpCargo.push(ret)
      }
      let bills = []
      for (let i = 0; i < cargo.length; i++) {
        let billNo = cargo[i].billNo
        if (bills.indexOf(billNo) === -1) bills.push(cargo[i].billNo)
      }
      let biss = [];
      let zds = [];
      for (let ind = 0; ind<cargo.length;ind++) {
        if(biss.indexOf(cargo[ind].billNo) === -1) {
          biss.push(cargo[ind].billNo)
        }
        if(zds.indexOf(cargo[ind].buName) === -1) {
          zds.push(cargo[ind].buName)
        }
      }

      LODOP.PRINT_INIT("送货单小票打印");
      LODOP.SET_LICENSES("","C748D766DD08B5AE84E6BC2F3A546E6C7C9","","");
      let tbhtml = '<table style="border-collapse:collapse;width:270px;"><tbody>'
      //
      tbhtml += "<tr><td colspan='2' style='padding: 5px 0;text-align: center;font-weight: bolder;font-size: 16px;width:270px;'>配送单("+item.licence+")</td></tr>"
      tbhtml += `<tr><td colspan='2' style='padding: 5px 0;text-align: left;font-weight: bolder;font-size: 14px;width:270px;'>终端数：${zds.length}</td></tr>`
      tbhtml += `<tr><td colspan='2' style='padding: 5px 0;text-align: left;font-weight: bolder;font-size: 14px;width:270px;'>票据数：${biss.length}</td></tr>`
      tbhtml += "<tr><td colspan='2' style='padding: 5px 0;text-align: left;font-weight: bolder;font-size: 14px;width:270px;'>本车商品汇总</td></tr>"
      for (let i = 0; i < gpGoods.length; i++) {
        tbhtml += '<tr><td style="padding: 2px 0;width: 200px;text-align: left;">'+gpGoods[i].invName+'</td><td style="width: 70px;text-align: right;">'+gpGoods[i].assQty+'</td></tr>'
      }
      tbhtml += "<tr><td style='border-bottom: 1px solid black;'></td><td style='border-bottom: 1px solid black'></td></tr>"
      tbhtml += '<tr><td style="padding: 2px 0;width: 200px;text-align: left;"></td><td style="width: 70px;text-align: right;padding-right: 17px;">'+sumCount+'</td></tr>'

      let pdetail = false
      for (let i = 0; i < gpCargo.length; i++) {
        if (this.printDetail.indexOf(gpCargo[i].tenantId) !== -1) {
          pdetail = true
        }
      }
     if (pdetail) {
       tbhtml += "<tr><td colspan='2' style='padding: 5px 0;text-align: left;font-weight: bolder;font-size: 14px;'>明细</td></tr>"
     }
     for (let i = 0; i < gpCargo.length; i++) {
        if (this.printDetail.indexOf(gpCargo[i].tenantId) !== -1) {
          let buName = gpCargo[i].buName
          let bNo = []
          let garr = gpBu[buName]
          for (let j = 0; j < garr.length; j++) {
            bNo.push(garr[j].billNo)
          }
          bNo = xe.uniq(bNo)
          let row = gpCargo[i]
          tbhtml += '<tr><td colspan="2" style="border-top: 1px solid black;padding-top: 10px;text-align: left;">'+row.buName+'</td></tr>'
          tbhtml += '<tr><td colspan="2" style="padding: 2px 0;word-break: break-all;text-align: left;"> '+bNo.join(',')+' </td></tr>'
          for (let j = 0; j < row.goods.length; j++) {
            let grow = row.goods[j]
            tbhtml += '<tr><td style="padding: 2px 0;text-align: left;">'+grow.invName+'</td><td style="text-align: right;">'+grow.assQty+'</td></tr>'
          }
          tbhtml += "<tr><td style='border-bottom: 1px solid black;'></td><td style='border-bottom: 1px solid black'></td></tr>"
          tbhtml += '<tr><td style="padding: 2px 0;width: 200px;text-align: left;"></td><td style="width: 70px;text-align: right;padding-right: 17px;">'+row.subCount+'</td></tr>'
        }
     }


      tbhtml += "<tr><td colspan='2' style='border-top: 1px solid black;height: 110px;'></td> </tr>"
      tbhtml += "<tr><td colspan='2' style='font-size: 12px;'>配送号："+item.billNo+","+tool.dayjs().format('YYYY/MM/DD HH:mm')+" </td> </tr>"
      tbhtml += '</tbody></table>'


      this.showPrint = tbhtml


      let dom = document.getElementById("printHtml");
      setTimeout(() => {
        let rects = dom.getClientRects()
        let barTop = tool.minus(rects[0].height, 120)
        if (barTop < 300) barTop += 20
        // LODOP.ADD_PRINT_BARCODE(barTop+'px', '90px', '100px', '100px', 'QRCode', '180001-' + item.id);
        this.top = barTop
        LODOP.SET_PRINT_PAGESIZE(3, '80mm',45,"") //这里3表示纵向打印且纸高“按内容的高度”；1385表示纸宽138.5mm；45表示页底空白4.5mm
        LODOP.ADD_PRINT_TABLE(40, 0, 800, rects[0].height, tbhtml)
        if (LODOP.SET_PRINTER_INDEX(sendPrintName)) {
          LODOP.PREVIEW();
          // LODOP.PRINT();
          this.chosePrint = false
        // LODOP.PREVIEW();
          if (LODOP.CVERSION) {
            CLODOP.On_Return = (TaskID,Value)=> {
              if (Value !== 0 || Value !== false) {
                tool.post('print/billPrintSuc', {cargoId: item.id}).then(ret => {})
              }
            }
          }

        } else {
          tool.err('读取小票打印机失败')
        }
      }, 50)
    },
    // 汇总单据中的商品
    groupGoods (checkedOrder) {
      let goods = []
      this.grpData = []
      for (let i = 0; i < checkedOrder.length; i++) {
        goods = goods.concat(checkedOrder[i])
      }
      let grpGoods = xe.groupBy(goods, 'invName')
      let ret = []
      for (let i in grpGoods) {
        let g = grpGoods[i][0]
        let total = xe.sum(grpGoods[i], item => tool.multiply(item.calNum, item.qty))
        let assQty = this.getAss(total, g)
        ret.push({invName: g.invName, spec: g.spec, unit: g.unit, assQty: assQty})
      }
      return ret
    },
    // 小单位算成辅助单位
    getAss (qty, row) {
      let spec = row.spec
      if (!spec) {
        tool.err(row.invName +' 规格换算不能为0')
        return
      }
      let mainQty = (qty - (qty%spec)) / spec
      let rqty = qty%spec
      let ass = ''
      if (mainQty) {
        ass = ass + mainQty + row.unit1
      }
      if (rqty) {
        ass = ass + rqty + row.unit2
      }
      return ass
    },
    hide () {
      this.$emit('hide')
    }
  },
}
</script>

<style scoped>

</style>
